package com.wen.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.wen.mall.dao.ProductDao;
import com.wen.mall.enums.ProductEnum;
import com.wen.mall.enums.ResponseEnum;
import com.wen.mall.form.CartAddForm;
import com.wen.mall.pojo.Cart;
import com.wen.mall.pojo.Product;
import com.wen.mall.service.CartService;
import com.wen.mall.utils.RedisUtil;
import com.wen.mall.vo.CartVo;
import com.wen.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CartServiceImpl implements CartService {
    private final static String CART_REDIS_KEY_TEMPLATE = "cart_%d";
    @Autowired
    private ProductDao productDao;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 添加到购物车
     *
     * @param uid
     * @param cartAddForm
     * @return
     */
    @Override
    public ResponseVo<CartVo> add(Integer uid, CartAddForm cartAddForm) {
        Product product = productDao.findById(cartAddForm.getProductId());
        //判断商品是否存在
        if (product == null) {
            return ResponseVo.error(ResponseEnum.PRODUCT_NOT_EXIT);
        }

        //判断商品是否在售
        if (!product.getStatus().equals(ProductEnum.ON_SALE.getCode())) {
            return ResponseVo.error(ResponseEnum.PRODUCT_OFF_SALE_DELETE);
        }
        //判断库存是否足够
        if (product.getStock() <= 0) {
            return ResponseVo.error(ResponseEnum.PRODUCT_STOCK_ERROR);
        }
        String key = String.format(CART_REDIS_KEY_TEMPLATE, uid);
        String value = JSON.toJSONString(new Cart(cartAddForm.getProductId(), 1, cartAddForm.getSelected()));
        redisUtil.set(key, value);
        return null;
    }
}
